package com.bcn.login_mybatis_demo.controller;

import com.bcn.login_mybatis_demo.annotation.PassToken;
import com.bcn.login_mybatis_demo.dto.LoginRequest;
import com.bcn.login_mybatis_demo.mapper.UserMapper;
import com.bcn.login_mybatis_demo.pojo.LogoutDTO;
import com.bcn.login_mybatis_demo.pojo.Role;
import com.bcn.login_mybatis_demo.pojo.User;
import com.bcn.login_mybatis_demo.pojo.UserDTO;
import com.bcn.login_mybatis_demo.result.ListResult;
import com.bcn.login_mybatis_demo.security.SecurityUserHolder;
import com.bcn.login_mybatis_demo.service.serviceImpl.RoleServiceImpl;
import com.bcn.login_mybatis_demo.service.serviceImpl.UserServiceImpl;
import com.bcn.login_mybatis_demo.util.Result;
import com.bcn.login_mybatis_demo.util.ResultUtil;
import com.bcn.login_mybatis_demo.util.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.List;

/**
 * @author 大白菜
 * @date Created in 2022/9/26 14:56
 */
@Slf4j
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserServiceImpl userServiceImpl;
    @Autowired
    private RoleServiceImpl roleServiceImpl;

    @PostMapping("/login")
    @PassToken
    public Result login(@RequestBody LoginRequest loginRequest) {
        String uact = loginRequest.getUact();
        String upwd = loginRequest.getUpwd();
        User user = userServiceImpl.loginService(uact,upwd);
        if(user != null){
            String userEpwd= user.getUpassword();
            if(upwd.equals(userEpwd)){
                String sign = JwtTokenUtils.sign(user.uid);
                return ResultUtil.success(new HashMap<String, String>() {{
                    put("token", sign);
                    put("uid", String.valueOf(user.uid));
                }});
            }else{
                return ResultUtil.error("密码错误");
            }
        }else{
            return ResultUtil.error("账号错误");
        }
    }

    @RequestMapping("/createUser")
    public Result register(@RequestBody User user) {
        String msg = userServiceImpl.registerService(user);
        if(("SUCCESS").equals(msg)){
            return ResultUtil.success(user);
        }else{
            return ResultUtil.error(msg);
        }
    }

    @PostMapping("/userList")
    public Result userList(@RequestBody(required = false) UserDTO userDTO) {
        if (userDTO == null) {
            userDTO = new UserDTO();  // 创建一个默认的 UserDTO 对象，或者你可以设置其它默认值
        }

        if (userDTO.getPageNo() == null || userDTO.getPageNo() <= 0) {
            userDTO.setPageNo(1);
        }
        // 如果没有传递 pageSize，设置为 10（每页10条数据）
        if (userDTO.getPageSize() == null || userDTO.getPageSize() <= 0) {
            userDTO.setPageSize(10);
        }
        List<User> data = userServiceImpl.getUserList(userDTO);
        long total = userServiceImpl.getUserCount(userDTO);
        ListResult listResult = new ListResult(data, total);

        return ResultUtil.success(listResult);
    }

    @RequestMapping("/info")
    public Result userDetail(@RequestParam(value = "uid", required = true) Integer uid) {
        if (uid == null) {
            return ResultUtil.error("请传入uid");
        }
        try {
            User user = userServiceImpl.queryDetail(uid);
            if (user != null) {
                return ResultUtil.success(user);
            } else {
                return ResultUtil.error("用户不存在");
            }
        } catch (Exception e) {
            return ResultUtil.error(e);
        }

    }

    @RequestMapping("delUser")
    public Result delUser(@RequestParam(value = "uid", required = true) Integer uid) {
        if (uid == null) {
            return ResultUtil.error("请传入uid");
        }
        try {
            String msg = userServiceImpl.delUser(uid);
            if (("SUCCESS").equals(msg)) {
                return ResultUtil.success("删除成功");
            } else {
                return ResultUtil.error("用户不存在");
            }
        } catch (Exception e) {
            return ResultUtil.error(e);
        }
    }

    @RequestMapping("/updateUser")
    public Result updateUser(@RequestBody UserDTO userDTO) {
        if(userDTO.getUid()==null){
            return ResultUtil.error("请传入参数uid");
        }
        User user = userServiceImpl.findUserById(userDTO.getUid());
        if (user == null) {
            return ResultUtil.error("用户不存在");
        }
        if(userDTO.getUname()!=null  && !userDTO.getUname().isEmpty()){
            user.setUname(userDTO.getUname());
        }
        if(userDTO.getUpassword()!=null && !userDTO.getUpassword().isEmpty()){
            user.setUpassword(userDTO.getUpassword());
        }
        if(userDTO.getUaccount()!=null && !userDTO.getUaccount().isEmpty()){
            user.setUaccount(userDTO.getUaccount());
        }

        // 如果传入了 roleid，则更新用户的角色
        if (userDTO.getRole_id() != null) {
            Integer role_id = userDTO.getRole_id();
            Role role = roleServiceImpl.getRoleByID(role_id);
            if(role!=null){
                user.setRoleId(userDTO.getRole_id());
            }else {
                return ResultUtil.error("角色ID不正确");
            }
        }

        String msg = userServiceImpl.updateUser(user);
        if (("SUCCESS").equals(msg)) {
            user = userServiceImpl.findUserById(userDTO.getUid()); // 拉取最新的数据
            return ResultUtil.success(user);
        }
        return ResultUtil.error(msg);
    }

//    @RequestMapping("/logout")
//    public Result logout(@RequestParam(value = "uid", required = true) Integer uid) {
//        if (uid == null) {
//            return ResultUtil.error("请传入uid");
//        }
//        // 根据 uid 或其他信息查找当前用户的 token
//        String token = JwtTokenUtils.getTokenByUid(uid);
//        if (token != null) {
//            // 将 token 标记为无效（这里需要你实现具体的逻辑）
//            JwtTokenUtils.deleteToken(token); // 假设这个方法可以处理 token 失效
//            return ResultUtil.success("成功退出登录");
//        } else {
//            return ResultUtil.error("未找到有效的 token");
//        }
//    }

    @PostMapping("/logout")
    public Result logout(@RequestBody LogoutDTO logoutDTO) {
        Integer uid = logoutDTO.getUid();
        if (uid == null) {
            return ResultUtil.error("请传入uid");
        }
        // 根据 uid 或其他信息查找当前用户的 token
        String token = JwtTokenUtils.getTokenByUid(uid);
        if (token != null) {
            // 将 token 标记为无效
            JwtTokenUtils.deleteToken(token);
            return ResultUtil.success("成功退出登录");
        } else {
            return ResultUtil.error("未找到有效的 token");
        }
    }

}
